package cn.com.w.bootfreemarker.util;

import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLDecoder;

public class Base64ImageUtil {

    Logger logger = LoggerFactory.getLogger(Base64ImageUtil.class);

    /**
     * 对路径下的图片进行64位编码
     *
     * @param imageUrl
     * @return
     * @throws IOException
     */
    public String ImageCoding(String imageUrl) throws IOException {
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();
            String path = URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource("").getFile(), "UTF-8");
            int a = path.indexOf("WEB-INF");
            String localUrl = "";
            if (a > -1) {
                localUrl = path.substring(0, a - 1);
            } else {
                localUrl = path;
            }
            File imageFile = new File(localUrl + imageUrl);
            // 将图片加载到内存
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            // 将图片加载到流中
            ImageIO.write(bufferedImage, "jpg", outputStream);
            // 对字节数组Base64编码
            logger.debug("图片字节数组为:" + outputStream.toByteArray());
            String image64 = Base64.encodeBase64String(outputStream.toByteArray());
            logger.debug("图片转码为:" + image64);
            return image64;
        } catch (MalformedURLException e1) {
            logger.error("对图片进行64位编码出错,可能为路径不对，未找到图片", e1);
            return "";
        } catch (IOException e) {
            logger.error("对图片进行64位编码出错,可能为路径不对，未找到图片", e);
            return "";
        } finally {
            outputStream.close();
        }
    }

    /**
     * 图片解码
     *
     * @param image64 image64字符串
     * @param name    图片名
     */
    public void ImageDecoding(String image64, String name) {
        if ("images/pqhc.png".equals(name)) {
            return;
        }
        //解码
        try {
            String sysPath = URLDecoder.decode(Thread.currentThread()
                    .getContextClassLoader().getResource("").getFile(), "UTF-8");
            int a = sysPath.indexOf("WEB-INF");
            String localUrl = "";
            if (a > -1) {
                localUrl = sysPath.substring(0, a - 1);
            } else {
                localUrl = sysPath;
            }
            File newFile = new File(localUrl + name);
            if (!newFile.getParentFile().exists()) {
                Boolean isPath = newFile.getParentFile().mkdirs();
                if (isPath) {
                    FileOutputStream write = new FileOutputStream(newFile);
                    byte[] decoderBytes = Base64.decodeBase64(image64);
                    write.write(decoderBytes);
                    write.close();
                }
            } else {
                FileOutputStream write = new FileOutputStream(newFile);
                byte[] decoderBytes = Base64.decodeBase64(image64);
                write.write(decoderBytes);
                write.close();
            }

        } catch (IOException e) {
            logger.error("对图片进行解码失败，可能图片编码为空", e);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        try {
            String path = URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource("").getFile(), "UTF-8");
            int a = path.indexOf("WEB-INF");
            String localUrl = "";
            if (a > -1) {
                localUrl = path.substring(0, a - 1);
            } else {
                localUrl = path;
            }
            System.out.println("==========");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


}
